package com.kethink;

import java.util.*;

/**
 * @Description create by xuxiaojun
 * date: 2018/12/26
 * Time: 11:13
 */
public class LeeCode_819 {

    public static String mostCommonWord(String paragraph, String[] banned) {

        String result = "";
        //先过滤所有标点符号，最后再去除多余的空格
        String paragraph2 = paragraph.replace(",", " ").replace(".", " ")
                .replace("!", " ").replace("'", " ")
                .replace(";", " ").replace("?", " ").replace("  ", " ");

        String paragraph3 = paragraph2.toLowerCase();

        String[] array = paragraph3.split(" ");
        //将paragraph放入map中，key为单词，value为出现次数
        HashMap<String,Integer> map = new HashMap<>();
        for(String string : array){
            if(map.containsKey(string)){
                map.put(string,map.get(string)+1);
            }else{
                map.put(string,1);
            }
        }
        //将map按照value降序排列
        ArrayList<Map.Entry<String,Integer>> list = new ArrayList<Map.Entry<String,Integer>>(map.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
            @Override
            public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                //降序排序
                return o2.getValue().compareTo(o1.getValue());
            }
        });

        //对比过滤禁用词
        boolean flag = false;
        for(int i = 0 ; i < list.size(); i++){
            for(int j = 0 ; j < banned.length ; j++){
                if(list.get(i).getKey().equals(banned[j])){
                    flag = true;
                    break;
                }
            }
            if (flag){
                flag = false;
                continue;
            }
            result = list.get(i).getKey();
            break;
        }
        return  result;
    }

    public static void main(String[] args){

//        String paragraph = "Bob hit a ball, the hit BALL flew far after it was hit.";
        String paragraph = "abc abc? abcd the jeff!";
        String[] banned = {"abc","abcd","jeff"};
        System.out.println(mostCommonWord(paragraph,banned));
    }
}
